package com.ruoyi.tenant.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.datasource.DynamicDataSource;
import com.ruoyi.tenant.dto.RegisterDTO;
import com.ruoyi.tenant.service.IInitTableService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.util.Map;

@Service
public class InitTableServiceImpl implements IInitTableService {

    @Override
    public AjaxResult initTable(RegisterDTO registerDTO){
        String tenantId = registerDTO.getTenantId().toLowerCase();

        try {
            DynamicDataSource dynamicDataSource = SpringUtils.getBean("dynamicDataSource");
            Map<Object, DataSource> resolvedDataSourcesMap = dynamicDataSource.getResolvedDataSources();
            DataSource dataSource = resolvedDataSourcesMap.get(tenantId);
            Connection connection = DataSourceUtils.getConnection(dataSource);

            ScriptRunner scriptRunner = new ScriptRunner(connection);
            //创建字符输出流，用于记录SQL执行日志
            StringWriter writer = new StringWriter();
            PrintWriter print = new PrintWriter(writer);
            //设置执行器日志输出
            scriptRunner.setLogWriter(print);
            //设置执行器错误日志输出
            scriptRunner.setErrorLogWriter(print);


            Resources.setCharset(Charset.forName("UTF-8"));
            Reader reader = Resources.getResourceAsReader("initsql/initTable.sql");
            scriptRunner.runScript(reader);

            reader.close();
            //关闭输入流
            scriptRunner.closeConnection();

        }catch (Exception e){
            throw new RuntimeException("读取初始化文件失败！");
        }
        return AjaxResult.success("初始化数据库成功");
    }
}
